package cn.kawa.system.service.impl;

import cn.kawa.system.domain.Role;
import cn.kawa.system.mapper.RoleMapper;
import cn.kawa.system.service.IRoleService;
import cn.kawa.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;


    @Override
    @Transactional
    public void add(Role role) {
        //1.先添加角色，获取 role 的自增长id
        super.add(role);

        addRoleRelevant(role);

    }

    /**
     *
     * @param role
     */
    private void addRoleRelevant(Role role) {
        List<Long> menus = role.getMenus();
        //2.添加角色拥有的菜单
        if(menus.size()>0){
            roleMapper.addRoleMenu(role.getId(),menus);
        }
        List<Long> permissions = role.getPermissions();
        //3.添加角色拥有的权限
        if(permissions.size()>0){
            roleMapper.addRolePermission(role.getId(),permissions);
        }
    }

    /**update方法
     * 思路： 删除关联的关系，再增加关联的关系，然后更新自己
     *
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {

        //1.删除RoleMenu
        roleMapper.delRoleMenuByRoleId(role.getId());
        //2.删除RolePermission
        roleMapper.delRolePermissionByRoleId(role.getId());

        addRoleRelevant(role);

        //更新自己的方法的位置不影响
        super.update(role);
    }

    @Override
    @Transactional
    public void delete(Long id) {

        //1.删除RoleMenu
        roleMapper.delRoleMenuByRoleId(id);
        //2.删除RolePermission
        roleMapper.delRolePermissionByRoleId(id);
        //3.删除EmployRole
        roleMapper.delEmployRoleByRoleId(id);

        //4.所有外键删除完在最后删除自己
        super.delete(id);


    }

    @Override
    @Transactional
    public void patchDel(List<Long> ids) {
        super.patchDel(ids);
        for (Long id : ids) {
            delete(id);
        }
    }
}
